import os 
import time 
class Recorder:
    '''
    实验数据记录器 模型开发
    ''' 
    data_file = None 
    data_dir = "records/"
    data_stream = None 
    log_cnt = 0
    save_interval = 50
    def __init__(self,expname,*head,print_also=False,save_interval = 50) -> None:
        '''
        @head:应该是一个元组描述数据表格的内容
        TODO 是否考虑使用pandas来记录数据
        '''
        try:
            self.mkdir()
            self.data_file = f"{self.data_dir}/{int(time.time())}-{expname}.log"
            self.data_stream = open(self.data_file,"w")
            self._log('index',*head)
            self.print_also_deco(print_also)
            self.save_interval = save_interval
        except Exception as e:
            print("ERROR whern create:{e}")
    def get_file_name(self):
        if self.data_file:
            return os.path.basename(self.data_file)
    def __del__(self):
        if(self.data_stream):
            self.data_stream.close()
    def print_also(*k,**kw):
        pass 

    def _log(self,*v):
        self.data_stream.write(','.join([str(_) for _ in v ])+'\n')
        self.print_also(','.join([str(_) for _ in v ]))
    def print_also_deco(self,print_also = False):
        if(print_also):
            def p_a(*k,**kw):
                print(*k,**kw)
            self.print_also = p_a
    def record(self,*v):
        self._log(self.log_cnt,*v)
        if self.log_cnt% self.save_interval == 0:
            self.data_stream.flush()
        self.log_cnt+=1

    def mkdir(self):
        if not os.path.exists(self.data_dir):
            os.mkdir(self.data_dir)
            #递归创建父目录
            

        
